package com.nulldev.util.web.YouTubeExtractor.advertising.internal;

import java.util.List;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Arrays.arrays.FastLists;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.YouTubeExtractor.advertising.YTEAdPlacement;
import com.nulldev.util.web.YouTubeExtractor.advertising.YTEAdPlacement.YTEAdPlacementType;
import com.nulldev.util.web.YouTubeExtractor.advertising.YTEAdvertisingMetadata;

public class YTEAdvertisingMetadataExtractor {

	private static final Logger log = LoggerFactory.getLogger();

	public static YTEAdvertisingMetadata makeFromPlaybackObject(final UniJsonValue object, final String videoID) {
		Variables.requireNonNull(object, "object");
		if (!object.contains("adPlacements"))
			return null;
		final UniJsonValue adPlacements = object.get("adPlacements");
		final List<YTEAdPlacement> placements = FastLists.list();
		adPlacements.asArray().forEach((_adPlacement) -> {
			final UniJsonValue adPlacement = _adPlacement.get("adPlacementRenderer");
			final String kind = adPlacement.get("config").get("adPlacementConfig").getString("kind");
			final UniJsonValue renderer = adPlacement.get("renderer");
			if (renderer.contains("imageCompanionAdRenderer")) {
				placements.add(new YTEAdPlacement(kind, YTEAdPlacementType.VIDEO_OVERLAY_AD, renderer.get("imageCompanionAdRenderer")));
			} else if (renderer.contains("actionCompanionAdRenderer")) {
				placements.add(new YTEAdPlacement(kind, YTEAdPlacementType.UI_PLACED_AD, renderer.get("actionCompanionAdRenderer")));
			} else if (renderer.contains("adBreakServiceRenderer")) {
				placements.add(new YTEAdPlacement(kind, YTEAdPlacementType.MIDROLL_AD, renderer.get("adBreakServiceRenderer")));
			} else if (renderer.contains("linearAdSequenceRenderer")) {
				placements.add(new YTEAdPlacement(kind, YTEAdPlacementType.PREROLL_OR_POSTROLL_BATCH, renderer.get("linearAdSequenceRenderer")));
			} else {
				log.warn("Unknown ad placement renderer: " + renderer);
			}
		});
		if (object.contains("playerAds")) {
			final UniJsonValue playerAds = object.get("playerAds").arrayGetContains("playerLegacyDesktopWatchAdsRenderer")
					.get("playerLegacyDesktopWatchAdsRenderer");
			if (playerAds == null || playerAds.isNull()) {
				log.warn("Failed to find playerLegacyDesktopWatchAdsRenderer...");
				log.debug(object.get("playerAds"));
				return new YTEAdvertisingMetadata(placements, false, false, false, null, videoID);
			} else {
				final String GUTparams = playerAds.get("gutParams").getString("tag");
				return new YTEAdvertisingMetadata(placements, playerAds.bool("showCompanion"), playerAds.bool("showInstream"), playerAds.bool("useGut"),
						GUTparams, videoID);
			}
		} else {
			log.warn("Failed to find playerAds...");
			return new YTEAdvertisingMetadata(placements, false, false, false, null, videoID);
		}
	}
}
